package com.yy.permissions_general.security.handler;

import com.yy.permissions_general.utils.FastJsonUtils;
import com.yy.permissions_general.utils.ResultUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: TODO 身份验证
 * @Author: YangYI
 * @Date: 2021/11/1
**/
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //修改编码格式
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json");
        if (e instanceof BadCredentialsException){
            httpServletResponse.getWriter().write(FastJsonUtils.toString(ResultUtil.error("用户名或密码错误~")));
        }else {
            httpServletResponse.getWriter().write(FastJsonUtils.toString(ResultUtil.error(e.getMessage())));
        }
    }
}
